import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'url'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import DefineOptions from 'unplugin-vue-define-options/vite'
import cesium from 'vite-plugin-cesium'
import path from 'path'
import Unocss from 'unocss/vite'

const configProxy = {
  test: {
    yueba: 'http://119.29.244.79:8997/',
    dahua: 'http://112.194.138.46:4077'
  },
  line: {
    ucenter: 'http://182.43.58.47:1326/',
    social: 'http://222.209.208.86:2260/'
  }
}

const getProxy = (name) => {
  return {
    '/yueba': {
      target: configProxy[name].yueba,
      changeOrigin: true,
      secure: false, // 跳过 SSL 验证
      rewrite: (path) => path.replace(/^\/yueba/, '')
    },
    '/evo-apigw': {
      target: configProxy[name].dahua,
      changeOrigin: true,
      secure: false // 跳过 SSL 验证
    }
  }
}

export default defineConfig(({ command, mode }) => {
  let alias = {
    '@': fileURLToPath(new URL('./src', import.meta.url))
  }

  return {
    base: './',
    plugins: [
      vue(),
      cesium(),
      DefineOptions(),
      vueJsx(),
      Unocss(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
    ],
    css: {
      preprocessorOptions: {
        scss: {
          // additionalData: '@import "./src/styles/var.scss";' // 全局变量
        }
      }
    },
    define: {
      'process.env': {}
    },
    resolve: {
      alias,
      extensions: ['.js', '.jsx', '.json', '.vue', '.css', '.scss']
    },
    server: {
      host: '0.0.0.0',
      port: 9711,
      hmr: true, // 启动热更新
      open: true,
      // https: true, // 开启 HTTPS
      proxy: getProxy('test'), // test：测试， line: 线上， dyw：丁云伟
      fs: {
        // 可以为项目根目录的上一级提供服务
        allow: ['..']
      }
    },
    build: {
      rollupOptions: {
        output: {
          // manualChunks 配置
          manualChunks: {
            // 将 React 相关库打包成单独的 chunk 中
            elementUl: ['element-plus'],
            dwylUi: ['dwyl-ui'],
            // 将组件库的代码打包
            echarts: ['echarts']
          }
        }
      }
    }
  }
})
